import {
  Controller,
  Get,
  Post,
  Query,
  Body,
  Patch,
  Delete,
  UseGuards,
} from '@nestjs/common';
import {
  ApiResponse,
  ApiOperation,
  ApiTags,
  ApiBearerAuth,
} from '@nestjs/swagger';
import { Search, SearchParams } from 'src/common/decorators/search.decorator';
import { UserService } from './user.service';
import { ToolUtil } from '@/utils/tool.util';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { ListUserDto, ListUserReturn } from './dto/list-user.dto';
import { UserEntity } from './entities/user.entity';
import { JwtAuthGuard } from '@/common/guards/jwt.guard';

@ApiTags('用户模块')
@ApiBearerAuth()
@Controller('user')
@UseGuards(JwtAuthGuard)
export class UserController {
  constructor(
    private readonly userService: UserService,
    private readonly toolUtil: ToolUtil,
  ) {}

  @Post()
  @ApiOperation({ summary: '创建用户' })
  @ApiResponse({ type: UserEntity })
  create(@Body() createUserDto: CreateUserDto): Promise<UserEntity> {
    const { salt, text } = this.toolUtil.addSalt(createUserDto.password);
    createUserDto.salt = salt; // 增加盐值
    createUserDto.password = text;
    return this.userService.create(createUserDto);
  }

  @Get('list')
  @ApiOperation({ summary: '查询用户列表' })
  @ApiResponse({ type: ListUserReturn })
  findAll(
    @Query() searchReqDto: ListUserDto,
    @SearchParams() searchParams: Search,
  ): Promise<ListUserReturn> {
    return this.userService.findAll(searchParams);
  }

  @Get()
  @ApiOperation({ summary: '查询用户详情' })
  @ApiResponse({ type: UserEntity })
  findOne(@Query('id') id: string): Promise<UserEntity> {
    return this.userService.findOne(id);
  }

  @Patch()
  @ApiOperation({ summary: '更新用户' })
  @ApiResponse({ example: 'success' })
  update(
    @Body('id') id: string,
    @Body() updateUserDto: UpdateUserDto,
  ): Promise<string> {
    return this.userService.update(id, updateUserDto);
  }

  @Delete()
  @ApiOperation({ summary: '删除用户' })
  @ApiResponse({ example: 'success' })
  remove(@Body('id') id: string): Promise<string> {
    return this.userService.remove(id);
  }
}
